package binarytree

func pathSum(root *TreeNode, targetSum int) [][]int {
	path := []int{}
	ans := [][]int{}

	var dfs func(*TreeNode, int)
	dfs = func(tn *TreeNode, i int) {
		if tn == nil {
			return
		}
		i -= tn.Val
		path = append(path, tn.Val)
		defer func() {
			path = path[:len(path)-1]
		}()

		if tn.Left == nil && tn.Right == nil && i == 0 {
			ans = append(ans, append([]int(nil), path...))
			// ans = append(ans, path)  这里会出错，因为传入的是引用类型，defer过后指针所指向的数组内容会变
			return
		}

		dfs(tn.Left, i)
		dfs(tn.Right, i)
	}

	dfs(root, targetSum)
	return ans

}
